package main

import (
	"flag"
	"log"
	"net"
)

func main() {
	port := flag.String("p", "9090", "端口")
	// 解析命令行参数写入注册的flag里
	flag.Parse()
	server, err := net.Listen("tcp", "0.0.0.0:"+*port)
	if err != nil {
		panic(err)
	}
	log.Printf("Listen: %s\n", server.Addr())
	defer server.Close()

	for {
		conn, err := server.Accept()
		if err != nil {
			continue
		}
		go handleConn(conn)
	}
}

func handleConn(conn net.Conn) {
	defer conn.Close()
	log.Printf("客户端地址：%s\n", conn.RemoteAddr().String())

	msg := readConn01(conn)
	log.Println("读取tcp结束")
	writeConn(conn, msg)
	log.Println("响应tcp结束")
}

func writeConn(conn net.Conn, msg string) {
	conn.Write([]byte("HTTP/1.1 200 OK\r\n"))
	conn.Write([]byte("Content-Type:text/plain:charset=UTF-8\r\n\r\n"))
	conn.Write([]byte(msg))
}

func readConn01(conn net.Conn) string {
	var request = make([]byte, 1000)
	len, err := conn.Read(request)
	if err != nil {
		log.Println("failed to read request contents")
		return ""
	}
	msgStr := string(request[:len])
	log.Printf("%v", msgStr)
	return msgStr
}
